package at.fhj.mobsecdev.cookit.activities;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import at.fhj.mobsecdev.cookit.R;
import at.fhj.mobsecdev.cookit.model.User;
import at.fhj.mobsecdev.cookit.webrequests.HashUtils;
import at.fhj.mobsecdev.cookit.webrequests.RegistrationWebCall;
import at.fhj.mobsecdev.cookit.webrequests.RegistrationWebCall.Registration;

/**
 * Activity for registration 
 */
public class RegistrationActivity extends Activity implements Registration{
	
	private EditText username;
	private EditText password;
	private EditText email;
	
	/* Minimum password criteria regex */
	private static final String PASSWORD_PATTERN = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{6,20})";
	private Pattern pattern;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_registration);
		
		username = (EditText) findViewById(R.id.username);
		password = (EditText) findViewById(R.id.password);
		email = (EditText) findViewById(R.id.email);
		
		pattern = Pattern.compile(PASSWORD_PATTERN);
		
	}
	
	public void registration(View view) {
		if(username.getText().length() == 0) {
			fieldError(String.format(getResources().getString(R.string.error_empty_field), "Username"));
		}else if(password.getText().length() == 0) {
			fieldError(String.format(getResources().getString(R.string.error_empty_field), "Password"));
		}else if(email.getText().length() == 0) {
			fieldError(String.format(getResources().getString(R.string.error_empty_field), "Email"));
		} else {
			Matcher matcher = pattern.matcher(password.getText().toString());
			if(matcher.matches() == false) {
				fieldError(getResources().getString(R.string.error_password_credentials));
			} else {
				User user = new User();
				user.setUsername(username.getText().toString());
				user.setPassword(HashUtils.hashPlaintextPassword(password.getText().toString()));
				user.setEmail(email.getText().toString());
				
				new RegistrationWebCall(this, RegistrationActivity.this).execute(user);
			}
		}
	}
	
	public void fieldError(String message) {
		Toast.makeText(this, message, Toast.LENGTH_LONG).show();
	}

	/* Callback methods for web service */
	
	@Override
	public void registrationSuccess() {
		Toast.makeText(this, getString(R.string.registration_successful), Toast.LENGTH_LONG).show();
		Intent i = new Intent(this, LoginActivity.class);
		startActivity(i);
	}

	@Override
	public void registrationFail(String error) {
		Toast.makeText(this, getString(R.string.registration_failed) + ": " + error, Toast.LENGTH_LONG).show();
		
	}
}
